import time
import socket
import json


#======成员变量======================
#判断机械臂是否启动
MAIsRun={"MechanicalArm_One":False,
         "MechanicalArm_Two":False,
         "MechanicalArm_Three":False,
         "photo_shoot":False,
         "glass_process":False}     


#控制函数线程变量
ST={"MechanicalArm_One":False,
    "MechanicalArm_Two":False,
    "MechanicalArm_Three":False,
    "photo_shoot":False,
    "glass_process":False}  



# 日志函数
flag=True
def print_log(str):
    if flag:
        print(str)
    else:
        pass

#===================网络处理函数=====================
#socket 的初始化
def socketinit(address,port):
    SERVER_ADDRESS = (address, port)
    # Create a socket object
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Bind the socket to the address and port
    server_socket.bind(SERVER_ADDRESS)

    # Listen for incoming connections
    server_socket.listen(5)
    return server_socket

#读出socket中的数据
def readsocket(client_socket):
    data=b''
    while True:
        temp_data=client_socket.recv(1024)
        data+=temp_data
        if(len(temp_data)<1024):
            break
    return data

def send_data(socket,data):
    try:
        # 将数据编码为字节流
        data_to_send = data.encode('utf-8')
        # 发送数据
        socket.send(data_to_send)
        print_log("数据发送成功")
    except Exception as e:
        print_log("发送数据时出现错误")
#=====================================================


#================JSON 处理函数=========================
# import new_arch
#解析json并存储到一个字典里面
def parse_json_and_store(json_data):
    try:
        parsed_data = json.loads(json_data)
        data_dict = {}
        for key, value in parsed_data.items():
            data_dict[key] = value
        return data_dict
    except json.JSONDecodeError as e:
        print(f"JSON decoding error: {e}")
        return None

#将字节转换为字符
def bytes_to_str(obj):
    if isinstance(obj, bytes):
        return obj.decode('utf-8')
    raise TypeError("Object of type 'bytes' is not JSON serializable")    

#将字典转换成字符串
def write_json(data_dict):
    #使用自定义的编码器将字节数据转换为字符串
    json_data = json.dumps(data_dict, default=bytes_to_str)
    return json_data


#将json格式化存储到一个文件中
# 注释   vscode
# Ctrl+K+C
# 取消//注释
# Ctrl+K+U
# 'r'       文本读取（默认）
# 'w'       文本写入，并先清空文件（慎用），文件不存在则创建
# 'x'       文本写，排它性创建，如果文件已存在则失败
# 'a'	      文本写，如果文件存在则在末尾追加，不存在则创建
def FormatStorageJson(filname,data,flag):
    with open(filname, flag) as write_f:
       #json.dump(data, write_f, indent=4, ensure_ascii=False) 
       json.dump(data, write_f)
       write_f.write('\n')

#校验数据是否正确
def is_json(msg):
    try:
        json.loads(msg)
        print_log("当前请求合格")
        return True
    except:
        print_log("当前请求不合格")
        return False
#=====================================================
    
#写入响应消息
def write_responseinfo(responsetype,args,data):   #时间自动帮你写上
    date_str  = time.strftime('%Y-%m-%d  %H:%M:%S', time.localtime())
    server_ip = socket.gethostbyname(socket.gethostname())
    response="response"
    dict = {'Type':response, 'Address':server_ip,'ResponseType':responsetype,'ArgInfo':args,'Time':date_str,'data':data}
    return write_json(dict)




import errno        
def CheckClient(client_socket):              #检查对端是否关闭
    # 设置套接字为非阻塞模式
    client_socket.setblocking(0)
    # 发送一个心跳包给客户端
    HBPacket = write_responseinfo("HeartBeat", " ", "die?")
    print_log(HBPacket)
    send_data(client_socket, HBPacket)
    client_socket.settimeout(0.5)
    try:
        received_data = client_socket.recv(1024)
        # 处理接收到的数据
        if received_data:
           print_log("接受到数据")
           return True
        else:
            print_log("没有接受到数据")
            return False
    except ConnectionAbortedError:
        # 处理客户端断开连接的情况
        print_log("客户端断开连接")
        return False
    except client_socket.timeout:
        print_log("客户端超时")
        return False
    except ConnectionResetError:
        print_log("主机强迫关闭一个现有连接")
    except Exception as e:
        print_log("error:{e}")
        return False
    finally:
        client_socket.close()
    
#修改全局变量
def AlterVariable(RequestType,flag=True):
    if RequestType in MAIsRun and RequestType in ST:
        MAIsRun[RequestType]=flag
        ST[RequestType]=flag
        print_log(RequestType+":修改成功")
        return 
    print_log(RequestType+":修改失败")

#关闭指定的线程
def StopThread(DictST,StopType):
    if StopType in DictST:   #判断要关闭的线程 是不是指定的函数
        DictST[StopType]=False   #关闭
        print_log(StopType+"关闭成功")
        return True
    print_log(StopType+"关闭失败")       
    return False